package com.lz.controller;

import com.lz.pojo.User;
import com.lz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;


    @RequestMapping("/search.html")
    public String search(){
        return "/WEB-INF/jsp/Login.jsp";
    }

    @RequestMapping("/search1.html")
  public String register(){
        return "/WEB-INF/jsp/UserRegister.jsp";
  }

    @RequestMapping("/login.html")
    public String login(Model model, String username, String password , HttpSession session){
        try {

            User user= userService.getUesrByNameAndPassword(username,password);
              session.setAttribute("SESSION_USER",user);
                return "/WEB-INF/jsp/shouye.jsp";

            } catch (Exception e){
              model.addAttribute("msg",e.getMessage());
              return "/WEB-INF/jsp/Login.jsp";
        }
    }

    @RequestMapping("/check.html")
    @ResponseBody
    public Map<String,Object> checkName(String username){
        int count=userService.getUserByName(username);
         if (count>0){
             Map<String,Object> result=new HashMap<>();
             result.put("status",false);
             result.put("msg","该用户已存在");
             return result;
         }else {
             Map<String,Object> result=new HashMap<>();
             result.put("status",true);
             result.put("msg","该用户可以注册");
             return result;
         }
    }
       @RequestMapping("/regist.html")
        public ModelAndView registe(User user,String repassword){
           try {

                 if (!user.getPassword().equals(repassword)){

                     throw new Exception("前后密码不一致");
                 }

            int count= userService.getUserByName(user.getUsername());
              if (count>0){
                throw new Exception("用户已经存在");
              }

           }catch (Exception e){
             return new ModelAndView("/WEB-INF/jsp/UserRegister.jsp","message",e.getMessage());
           }
                userService.addUser(user);
           return new ModelAndView("/WEB-INF/jsp/Login.jsp");
       }



}
